<template>
  <div class="container">
    <el-dialog
      title="添加行采订单"
      :visible.sync="addDialog.centerDialogVisible"
      @open="openData"
      @close="cancel"
      center
      width="99%"
    >
      <el-select
        style="margin-bottom: 5px"
        v-model="search.organization"
        :multiple="false"
        filterable
        remote
        center
        reserve-keyword
        placeholder="请选择机构"
        :remote-method="organizationMethod"
        :loading="insides.loading"
        @change="organizationChange"
      >
        <el-option
          v-for="item in insides.option"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-select>
      <div class="top">
        <el-select
          size="small"
          v-model="search.supplier_code"
          :multiple="false"
          filterable
          remote
          center
          reserve-keyword
          placeholder="请选择供应商"
          :remote-method="supplierRemoteMethod"
          :loading="supplierCenter.loading"
        >
          <el-option
            v-for="item in supplierCenter.option"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </div>
      <div class="top">
        <el-select
          size="small"
          v-model="search.buyer_code"
          :multiple="false"
          filterable
          remote
          center
          reserve-keyword
          placeholder="请选择采购员"
          :remote-method="insidePurchaseMethod"
          :loading="purchase.loading"
          @change="getPurchases(search.buyer_code)"
        >
          <el-option
            v-for="item in purchase.option"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </div>
      <div class="top">
        <el-select
          :multiple="false"
          filterable
          remote
          center
          reserve-keyword
          v-model="selectList"
          placeholder="请搜索选择配送中心"
          :remote-method="selectListsRemoteMethod"
          :loading="selectLists.loading"
          @change="distribution(selectList)"
        >
          <el-option
            v-for="item in selectLists.option"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </div>

      <div class="top">
        <el-select
          :multiple="false"
          filterable
          remote
          center
          reserve-keyword
          v-model="commodity"
          placeholder="请搜索选择商品"
          :remote-method="insideRemoteMethod"
          :loading="inside.loading"
        >
          <el-option
            v-for="item in inside.option"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-button
          size="medium"
          type="primary"
          class="handleSearch"
          icon="el-icon-search"
          @click="addGoods()"
          >添加</el-button
        >
        <el-button
          size="medium"
          type="primary"
          class="handleSearch"
          icon="el-icon-upload"
          @click="download()"
          >模板下载</el-button
        >

        <el-upload
          class="upload-demo"
          style="display: inline; margin-left: 10px"
          action="#"
          :show-file-list="false"
          :http-request="handleAvatarSuccess"
        >
          <el-button
            size="medium"
            type="primary"
            class="handleSearch"
            icon="el-icon-circle-plus"
            >导入商品</el-button
          >
        </el-upload>
      </div>
      <div class="noList" v-if="noList">
        <p style="color: red">ERP不存在的商品：</p>
        <el-tag v-for="tag in tags" :key="tag.name">
          {{ tag.name }}
        </el-tag>
      </div>
      <el-table
        :data="tableData"
        border
        max-height="500"
        style="width: 100%"
        empty-text="暂无数据"
        :summary-method="getSummaries"
        show-summary
      >
        <el-table-column
          prop="goods_name"
          label="商品名称"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="erp_goods_code"
          label="商品编码"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="goods_spec"
          label="规格"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="category_code"
          label="分类编码"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="category_name"
          label="分类名称"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="goods_unit"
          label="单位"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="bar_code"
          label="条形码"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="purchasePrice"
          label="采购加价"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="fixed_price"
          label="门店参考价"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="stockRemoval"
          label="出库价"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="totalPrices"
          label="出库价总价"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="costPrices"
          label="成本总价"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="reference_price"
          label="入库参考价"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="cost_price"
          label="成本价"
          align="center"
          width="150px"
        >
          <template slot-scope="scope">
            <el-input-number
              size="small"
              @change="markup(scope)"
              :controls="false"
              :max="
                scope.row.reference_price > 0
                  ? scope.row.reference_price
                  : Infinity
              "
              v-model="scope.row.cost_price"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center" width="150px">
          <template slot-scope="scope">
            <el-input-number
              size="small"
              @change="orderNum(scope)"
              :controls="false"
              v-model="scope.row.order_num"
            ></el-input-number>
          </template>
        </el-table-column>

        <el-table-column label="加价" align="center" width="150px">
          <template slot-scope="scope">
            <el-input-number
              size="small"
              :disabled="scope.row.m_type == 2"
              @change="markup(scope)"
              :controls="false"
              v-model="scope.row.markup"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column
          prop="box_qty"
          label="件数"
          align="center"
          width="150px"
        >
          <!-- <template slot-scope="scope">
            <el-input-number
              size="small"
              :controls="false"
              v-model="scope.row.box_qty"
            ></el-input-number>
          </template> -->
        </el-table-column>
        <el-table-column label="预提" align="center" width="150px">
          <template slot-scope="scope">
            <div>{{ scope.row.withholding_fee }}</div>
          </template>
        </el-table-column>
        <el-table-column width="150px" label="入库规格" align="center">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.rk_spec"
              @change="sonCount(scope)"
              placeholder="请选择"
            >
              <el-option
                v-for="item in scope.row.SonCountsList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="生产日期" align="center" width="250px">
          <template slot-scope="scope">
            <el-date-picker
              value-format="yyyy-MM-dd HH:mm:ss"
              v-model="scope.row.produce_date"
              type="datetime"
              placeholder="选择日期时间"
            >
            </el-date-picker>
          </template>
        </el-table-column>
        <el-table-column label="保质期（天）" align="center" width="150px">
          <template slot-scope="scope">
            <el-input-number
              size="small"
              :controls="false"
              v-model="scope.row.shelf_life"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="到期日" align="center" width="250px">
          <template slot-scope="scope">
            <el-date-picker
              value-format="yyyy-MM-dd HH:mm:ss"
              v-model="scope.row.due_date"
              type="datetime"
              placeholder="选择日期时间"
            >
            </el-date-picker>
          </template>
        </el-table-column>
        <el-table-column label="包装箱" align="center" width="150px">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.package_box_id"
              @change="rdcBox(scope)"
              placeholder="请选择"
            >
              <el-option
                v-for="item in boxList"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="包装箱规格" align="center" width="200px">
          <template slot-scope="scope">
            <div>
              <el-input-number
                size="small"
                :precision="4"
                v-if="scope.row.rdcType"
                :controls="false"
                v-model="scope.row.package_box_specInp"
              ></el-input-number>
              <span v-else>{{ scope.row.package_box_specInp }}</span>
              <span
                v-if="scope.row.rdcType"
                style="line-height: 30px;margin-left: 5px;"
                >KG</span
              >
              <span v-else style="line-height: 30px;margin-left: 5px;">个</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" width="250px">
          <template slot-scope="scope">
            <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="scope.row.notes"
            >
            </el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="150px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="danger"
              @click="remove(scope)"
              icon="el-icon-delete"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="primary"
              class="handleSearch"
              icon="el-icon-circle-plus"
              @click="addSpec(scope)"
              >添加规格</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-dialog
        width="400px"
        title="添加规格"
        center
        :visible.sync="spaceDialog"
        append-to-body
        @close="cancelSpec"
      >
        <el-form label-width="100px" label-position="center">
          <el-form-item label="规格：">
            <el-input-number
              size="small"
              :controls="false"
              v-model="spec"
            ></el-input-number>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="cancelSpec">取 消</el-button>
          <el-button type="primary" @click="specNum()">确 定</el-button>
        </span>
      </el-dialog>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  selectErpGoodsData,
  getSupplierByBindGoods,
  addOrderInfo,
  selectErpOrderGoodsData,
  addHangCaiOrderInfo,
  getPackageBoxData
} from "@/api/superOrder/superOrderList";
import { getToken } from "@/utils/auth";
import { Loading } from "element-ui";
import { getOrgData } from "@/api/middleorder/middleorderlist";
import { getOpenOrgData } from "@/api/middleorder/middleorderlist";
import { selectRdcData } from "@/api/select/select";
import { selectSupplierData } from "@/api/supplier/supplierList"; //供应商
import { getList } from "@/api/putStorage/putStotageList"; //采购员
export default {
  props: {
    addDialog: Object
  },
  data() {
    return {
      tableData: [],
      unAvgBatchData: [],
      commodity: "",
      is_assign: false,
      noList: false,
      tags: [],
      inside: {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false
      },
      insides: {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false
      },
      supplierCenter: {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false
      },
      purchase: {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false
      },
      search: {
        goods_code: "",
        org_code: "",
        supplier_code: "",
        buyer_code: "",
        buyer_name: "",
        buyer_id: "",
        organization: ""
      },
      priceNum: 0,
      selectLists: {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false
      },
      selectList: "",
      distributionCenter: {
        warehouse_code: "",
        rdc_code: ""
      },
      spaceDialog: false,
      spec: "0",
      specId: "",
      boxData: {},
      boxList: [],
      rdc: null
    };
  },
  methods: {
    //取消
    cancel() {
      this.addDialog.centerDialogVisible = false;
      this.tags = [];
      this.inside = {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false
      };
      this.insides = {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false
      };
      this.purchase = {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false
      };
      this.supplierCenter = {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false
      };
      this.commodity = "";
      this.tableData = [];
      this.search = {
        goods_code: "",
        org_code: "",
        supplier_code: "",
        buyer_code: "",
        buyer_name: "",
        buyer_id: "",
        organization: ""
      };
      this.selectLists = {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false
      };
      this.selectList = "";
      this.distributionCenter = {
        warehouse_code: "",
        rdc_code: ""
      };
      this.noList = false;
    },
    getData() {
      let data = {
        page: 1,
        limit: 500,
        goods_code: this.search.goods_code,
        rdc_code: this.distributionCenter.rdc_code,
        warehouse_code: this.distributionCenter.warehouse_code,
        is_can_use: 3
      };
      //获取商品
      selectErpOrderGoodsData(data).then(res => {
        this.goodsList = res.data.paginate.data;
        if (res.data.paginate.data) {
          this.inside.option = res.data.paginate.data.map(item => {
            return { value: `${item.Code}`, label: `${item.Name}` };
          });
        }
      });
    },
    openData() {
      this.getDatas();
      this.getSupplier();
      this.getselsetData();
      this.getPurchase();
      this.getPackageBox();
    },
    getDatas() {
      let data = {
        page: 1,
        limit: 500,
        key: this.search.org_code
      };
      //获取机构
      getOpenOrgData(data).then(res => {
        if (res.data) {
          this.insides.option = res.data.map(item => {
            return {
              value: `${item.erp_org_code}`,
              label: `${item.name}`,
              org_area_code: `${item.org_area_code}`
            };
          });
        }
      });
    },
    getSupplier(name = "") {
      let data = {
        page: 1,
        limit: 100,
        name
      };
      //获取供应商列表
      selectSupplierData(data).then(res => {
        this.supplierCenter.option = res.data.paginate.data.map(item => {
          return {
            value: `${item.supplier_code}`,
            label: `${item.supplier_name}`
          };
        });
      });
    },

    // 嵌套搜索供应商数据
    supplierRemoteMethod(query) {
      if (query !== "") {
        this.getSupplier(query);
      } else {
        this.supplierCenter.option = [];
      }
    },
    getPackageBox() {
      getPackageBoxData().then(res => {
        this.boxData = res.data.package;
        this.rdc = res.data.rdc;
      });
    },
    rdcBox(scope) {
      let id = scope.row.package_box_id;
      this.boxList.forEach((res, index) => {
        if (res.id == scope.row.package_box_id) {
          if (index == 0) {
            scope.row.rdcType = false;
            scope.row.package_box_specInp = 1;
          } else {
            scope.row.rdcType = true;
            scope.row.package_box_specInp = scope.row.package_box_spec;
          }
        }
      });
      console.log(scope.row.package_box_id, 9999);
    },
    getselsetData() {
      let data = {
        page: 1,
        limit: 500,
        code_or_name: this.search.selectnamecode
      };
      //获取配送中心
      selectRdcData(data).then(res => {
        if (res.data.paginate.data) {
          this.selectLists.option = res.data.paginate.data.map(item => {
            return {
              value: `${item.d_code}`,
              label: `${item.d_name}`,
              warehouse_code: `${item.warehouse_code}`,
              org_area_code: `${item.area_code}`,
              rdc_attr: `${item.rdc_attr}`
            };
          });
        }
      });
    },
    // 嵌套搜索配送方式数据
    selectListsRemoteMethod(query) {
      if (query !== "") {
        this.houseList(query);
      } else {
        this.selectLists.option = [];
      }
    },
    //获取配送数据
    houseList(query) {
      this.search.selectnamecode = query;
      this.getselsetData();
    },
    distribution(code) {
      let arr = this.selectLists.option.filter(res => {
        return res.value == code;
      });
      console.log(arr, 8888);
      if (arr[0].rdc_attr == "0") {
        this.boxList = this.boxData.shengnei;
      } else {
        this.boxList = this.boxData.shengwai;
      }
      this.distributionCenter = {
        warehouse_code: arr[0].warehouse_code,
        rdc_code: arr[0].value
      };
      this.tableData = [];
      this.inside = {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false
      };
      this.commodity = "";
    },
    //修改加价率和预提
    markup(scope, len = "") {
      console.log(scope.row, 89898989);
      let cost_price = scope.row.cost_price ? scope.row.cost_price : 0;
      let markup = scope.row.markup ? scope.row.markup : 0;
      if (scope.row.m_type == 2) {
        markup = (scope.row.cost_price * (scope.row.markups / 100)).toFixed(4);
      }
      scope.row.markup = markup;

      let order_num = scope.row.order_num ? scope.row.order_num : 0;
      scope.row.costPrices = (
        parseFloat(cost_price) * parseFloat(order_num)
      ).toFixed(4);
      scope.row.purchasePrice = parseInt(scope.row.BuyerProfitMode)
        ? parseFloat(scope.row.BuyerProfitRate)
        : (
            (parseFloat(cost_price) + parseFloat(markup)) *
            parseFloat(scope.row.BuyerProfitRate)
          ).toFixed(4);
      scope.row.stockRemoval = parseFloat(
        (
          parseFloat(cost_price) +
          parseFloat(markup) +
          +parseFloat(scope.row.purchasePrice)
        ).toFixed(4)
      );
      scope.row.totalPrices = (scope.row.stockRemoval * order_num).toFixed(4);

      this.$set(this.tableData, len - 1, scope.row);
    },
    //修改数量
    orderNum(scope) {
      let order_num = scope.row.order_num ? scope.row.order_num : 0;
      scope.row.costPrices = (
        parseFloat(scope.row.cost_price) * parseFloat(order_num)
      ).toFixed(4);
      scope.row.totalPrices = (
        parseFloat(scope.row.stockRemoval) * parseFloat(order_num)
      ).toFixed(4);
      scope.row.box_qty = (
        parseFloat(order_num) / parseFloat(scope.row.rk_spec)
      ).toFixed(4);
      this.$set(this.tableData, scope.$index, scope.row);
    },
    //删除
    remove(scope) {
      let id = scope.row.erp_goods_code;
      this.tableData.forEach((res, index) => {
        if (res.erp_goods_code == id) {
          this.tableData.splice(index, 1);
        }
      });
      this.priceNum = 0;
    },
    // 添加商品
    addGoods() {
      if (this.search.organization) {
        if (this.commodity) {
          let every = this.tableData.filter(res => {
            return (
              res.Code == this.commodity || res.erp_goods_code == this.commodity
            );
          });
          if (every.length == 0) {
            let arr = this.goodsList.filter(res => {
              return res.Code == this.commodity;
            });
            console.log(arr, 99999);
            this.openSupplie(arr[0]);
          } else {
            this.$message({
              type: "info",
              message: "该商品已添加"
            });
          }
        } else {
          this.$message({
            type: "info",
            message: "请选择商品"
          });
        }
      } else {
        this.$message({
          type: "info",
          message: "请选择机构"
        });
      }
    },
    //总价
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "总价";
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          if (index != 10 && index != 11) {
            sums[index] = "";
          } else {
            sums[index] = sums[index].toFixed(4);
          }
        } else {
          sums[index] = "";
        }
      });

      return sums;
    },
    // 获取商品方法
    insideRemoteMethod(query) {
      if (query !== "") {
        this.getSupplierList(query);
      } else {
        this.inside.options = [];
      }
    },
    //获取商品数据
    getSupplierList(query) {
      this.search.goods_code = query;
      this.getData();
    },
    // 嵌套搜索供应商数据
    organizationMethod(query) {
      if (query !== "") {
        this.organizationList(query);
      } else {
        this.insides.option = [];
      }
    },
    getPurchase(key = "") {
      let data = {
        page: 1,
        limit: 100,
        key
      };
      //获取商超采购员列表
      getList(data).then(res => {
        this.purchase.option = res.data.map(item => {
          return {
            value: item.code,
            label: item.name,
            id: item.id
          };
        });
      });
    },
    insidePurchaseMethod(query) {
      if (query !== "") {
        this.getPurchase(query);
      } else {
        this.purchase.option = [];
      }
    },
    getPurchases(e) {
      let data = this.purchase.option.filter(res => {
        return res.value == e;
      });
      this.search.buyer_code = data[0].value;
      this.search.buyer_name = data[0].label;
      this.search.buyer_id = data[0].id;
    },
    //获取供应商数据
    organizationList(query) {
      this.search.org_code = query;
      this.getDatas();
    },

    openSupplie(scope) {
      let sonArr = scope.SonCounts.split(",");
      let bool = sonArr.filter(res => {
        return (
          parseFloat(res).toFixed(4) == parseFloat(scope.rk_spec).toFixed(4)
        );
      });
      if (bool.length == 0) {
        sonArr.push(scope.rk_spec);
      }
      let sonObj = [];
      sonArr.forEach(res => {
        if (parseFloat(res).toFixed(4) == 0) {
          sonObj.push({
            value: 1,
            label: 1
          });
        } else {
          sonObj.push({
            value: res,
            label: res
          });
        }
      });
      let reference_price = 0;
      if (this.search.organization) {
        let orgArr = this.insides.option.filter(res => {
          return res.value == this.search.organization;
        });
        let referencePrice = scope.reference_price[2];
        reference_price = referencePrice
          ? referencePrice[orgArr[0].org_area_code]
            ? referencePrice[orgArr[0].org_area_code].reference_price
            : 0
          : 0;
      }
      let markup = 0;
      if (scope.m_type == 1) {
        markup = scope.markup;
      } else {
        console.log(reference_price, 5656);
        markup = (reference_price * (scope.markup / 100)).toFixed(4);
      }
      let rdcBool = null;
      if (this.rdc.length > 0) {
        rdcBool = this.rdc.some(res => {
          return res == this.distributionCenter.rdc_code;
        });
      }
      this.tableData.push({
        erp_goods_code: scope.Code,
        goods_name: scope.Name,
        bar_code: scope.BarCode,
        goods_unit: scope.Unit,
        goods_spec: scope.Spec || "",
        category_code: scope.ClassCode,
        category_name: scope.ClassName,
        SonCountsList: JSON.parse(JSON.stringify(sonObj)),
        is_zc: 1,
        cost_price: reference_price,
        // stockRemoval: scope.withholding_fee,
        stockRemoval: scope.BuyerProfitMode ? scope.BuyerProfitRate : 0,
        fixed_price: scope.fixed_price,
        purchasePrice: scope.BuyerProfitMode ? scope.BuyerProfitRate : 0,
        totalPrices: 0,
        BuyerProfitRate: scope.BuyerProfitRate,
        BuyerProfitMode: scope.BuyerProfitMode,
        package_box_id: rdcBool ? this.boxList[1].id : this.boxList[0].id,
        package_box_specInp: rdcBool ? scope.package_box_spec : 1,
        package_box_spec: scope.package_box_spec,
        rdcType: rdcBool ? true : false,
        costPrices: 0,
        order_num: 0,
        box_qty: 0,
        produce_date: "",
        shelf_life: "",
        due_date: "",
        notes: "",
        rk_spec: scope.rk_spec,
        // withholding_fee: scope.withholding_fee,
        withholding_fee: 0.0,
        m_type: scope.m_type,
        markup: markup,
        markups: scope.markup,
        reference_price: reference_price
      });
      console.log(this.tableData, 66666);
      let center = {};
      let len = this.tableData.length;
      center.row = this.tableData[len - 1];
      this.markup(center, len);
    },
    organizationChange() {
      this.tableData = [];
    },
    //导入商品
    handleAvatarSuccess(param) {
      if (this.search.organization) {
        this.noList = false;
        this.tags = [];
        let loading = Loading.service({
          lock: true,
          text: "Loading",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.1)"
        });
        let orgArr = this.insides.option.filter(res => {
          return res.value == this.search.organization;
        });
        let data = new window.FormData();
        data.append("goods_file", param.file);
        data.append("token", getToken());
        data.append("org_code", orgArr[0].value);
        data.append("supplier_code", this.search.supplier_code);
        data.append("org_area_code", orgArr[0].org_area_code);
        data.append("rdc_code", this.distributionCenter.rdc_code);
        data.append("warehouse_code", this.distributionCenter.warehouse_code);
        this.$axios
          .post("/smkapi/order/importHangCaiOrderGoods", data)
          .then(res => {
            loading.close();
            if (res.data.code == 0) {
              if (res.data.data.tips.length > 0) {
                res.data.data.tips.forEach(item => {
                  this.tags.push({
                    name: `${item.goods_name}(${item.goods_code})`
                  });
                });
                this.noList = true;
              }
              this.$message({
                message: res.data.message || res.data.msg,
                type: "success"
              });
              this.tableData = [];

              res.data.data.list.forEach(scope => {
                let sonObj = [
                  {
                    value: parseFloat(scope.rk_spec),
                    label: parseFloat(scope.rk_spec)
                  }
                ];
                let purchasePrice = parseInt(scope.BuyerProfitMode)
                  ? parseFloat(scope.BuyerProfitRate)
                  : (
                      (parseFloat(scope.cost_price) +
                        parseFloat(scope.markup)) *
                      parseFloat(scope.BuyerProfitRate)
                    ).toFixed(4);
                let stockRemoval = (
                  parseFloat(scope.cost_price) +
                  parseFloat(scope.markup) +
                  parseFloat(purchasePrice)
                )
                  // +parseFloat(scope.withholding_fee)
                  .toFixed(4);
                let totalPrices = (
                  stockRemoval * parseFloat(scope.order_num)
                ).toFixed(4);
                let costPrices = (
                  parseFloat(scope.cost_price) * parseFloat(scope.order_num)
                ).toFixed(4);
                let rdcBool = null;
                if (this.rdc.length > 0) {
                  rdcBool = this.rdc.some(res => {
                    return res == this.distributionCenter.rdc_code;
                  });
                }
                this.tableData.push({
                  erp_goods_code: scope.Code,
                  goods_name: scope.Name,
                  bar_code: scope.BarCode,
                  goods_unit: scope.Unit,
                  goods_spec: scope.Spec || "",
                  category_code: scope.ClassCode,
                  category_name: scope.ClassName,
                  SonCountsList: JSON.parse(JSON.stringify(sonObj)),
                  is_zc: 1,
                  cost_price: scope.cost_price,
                  stockRemoval: stockRemoval,
                  fixed_price: scope.fixed_price,
                  purchasePrice: purchasePrice,
                  totalPrices: totalPrices,
                  costPrices: costPrices,
                  BuyerProfitRate: scope.BuyerProfitRate,
                  BuyerProfitMode: scope.BuyerProfitMode,
                  order_num: scope.order_num,
                  box_qty: scope.box_qty,
                  produce_date: scope.produce_date,
                  shelf_life: scope.shelf_life,
                  due_date: "",
                  rk_spec: parseFloat(scope.rk_spec),
                  // withholding_fee: scope.withholding_fee,
                  withholding_fee: 0.0,
                  reference_price: scope.reference_price,
                  markup: scope.markup,
                  package_box_id: rdcBool
                    ? this.boxList[1].id
                    : this.boxList[0].id,
                  package_box_specInp: rdcBool ? scope.package_box_spec : 1,
                  package_box_spec: scope.package_box_spec,
                  rdcType: rdcBool ? true : false,
                  notes: scope.notes
                });
              });
            } else {
              this.$message({
                type: "info",
                message: res.data.message || res.data.msg
              });
            }
          });
      } else {
        this.$message({
          type: "info",
          message: "请选择机构"
        });
      }
    },
    //下载模板
    download() {
      this.$confirm("是否下载模板?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let link = document.createElement("a");
          link.href =
            this.$axios.defaults.baseURL +
            "/smkapi/order/downloadTemplte?token=" +
            getToken() +
            "&flag=1";
          link.click();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },
    //添加规格
    addSpec(scope) {
      this.specId = scope.row.bar_code;
      this.spaceDialog = true;
    },
    cancelSpec() {
      this.spaceDialog = false;
      this.spec = 0;
      this.specId = "";
    },
    //规格确定
    specNum() {
      this.tableData.forEach((res, index) => {
        if (res.bar_code === this.specId) {
          res.SonCountsList.push({
            value: this.spec,
            label: this.spec
          });
          this.$set(this.tableData, index, res);
          this.cancelSpec();
        }
      });
    },
    sonCount(scope) {
      if (scope.row.order_num) {
        scope.row.box_qty = (
          parseFloat(scope.row.order_num) / parseFloat(scope.row.rk_spec)
        ).toFixed(4);
        this.$set(this.tableData, scope.$index, scope.row);
      }
    },
    //确定
    confirm() {
      if (this.search.organization == "") {
        this.$message({
          type: "info",
          message: "请选择机构"
        });
      } else if (this.search.supplier_code == "") {
        this.$message({
          type: "info",
          message: "请选择供应商"
        });
      } else if (this.search.buyer_code == "") {
        this.$message({
          type: "info",
          message: "请选择采购员"
        });
      } else if (this.selectList == "") {
        this.$message({
          type: "info",
          message: "请选择配送中心"
        });
      } else if (this.tableData.length == "") {
        this.$message({
          type: "info",
          message: "请添加商品"
        });
      } else {
        let arr = [];
        this.tableData.forEach(res => {
          arr.push({
            erp_goods_code: res.erp_goods_code,
            goods_name: res.goods_name,
            bar_code: res.bar_code,
            goods_unit: res.goods_unit,
            goods_spec: res.goods_spec || "",
            category_code: res.category_code,
            category_name: res.category_name,
            is_zc: 1,
            cost_price: res.cost_price,
            order_num: res.order_num,
            box_qty: res.box_qty,
            withholding_fee: res.withholding_fee,
            markup: res.markup,
            produce_date: res.produce_date,
            shelf_life: res.shelf_life,
            due_date: res.due_date,
            rk_spec: res.rk_spec,
            buyerprofitmode: res.BuyerProfitMode,
            buyerprofitrate: res.BuyerProfitRate,
            package_box_id: res.package_box_id,
            package_box_spec: res.package_box_specInp,
            notes: res.notes
          });
        });
        let data = {
          erp_org_code: this.search.organization,
          goods: JSON.stringify(arr),
          dccode: this.selectList,
          supplier_code: this.search.supplier_code,
          buyer_code: this.search.buyer_code,
          buyer_name: this.search.buyer_name,
          buyer_id: this.search.buyer_id
        };
        addHangCaiOrderInfo(data).then(res => {
          if (res.code == 0) {
            this.$message({
              type: "success",
              message: res.msg || res.message
            });
            this.$emit("upData");
            this.cancel();
          }
        });
      }
    }
  }
};
</script>
<style scoped>
.pagination {
  text-align: right;
  padding: 10px;
}

.top {
  margin-bottom: 5px;
}

.noList {
  margin: 10px 0;
}
</style>
